import React, { Component } from 'react'
// 引入 connect 用于连接 UI 与 redux 
import { connect } from "react-redux"
import {
    increment,
    decrement,
    incrementAsync
} from "../../redux/action/count"

// 注册 UI 组件
class Count extends Component {
    // 加法
    increment = () => {
        const { value } = this.selectNumber;
        this.props.increment(value * 1)
    }
    // 减法
    decrement = () => {
        const { value } = this.selectNumber;
        this.props.decrement(value * 1)
    }
    // 当前求和为奇数再加
    incrementIfOdd = () => {
        const { value } = this.selectNumber;
        if (this.props.count % 2 !== 0) {
            this.props.increment(value * 1)
        }
    }
    // 异步加
    incrementAsync = () => {
        const { value } = this.selectNumber;
        this.props.incrementAsync(value * 1, 500)
    }
    render() {
        // console.log("UI组件接收到的消息是",this.props)
        return (
            <div>
                <h1>我是 Count 组件</h1>
                <h3>下方组件总人数为： {this.props.personList}</h3>
                <h3>当前求和为：{this.props.count}</h3>
                <select ref={c => this.selectNumber = c}>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select>&nbsp;
                <button onClick={this.increment}>+</button>&nbsp;
                <button onClick={this.decrement}>-</button>&nbsp;
                <button onClick={this.incrementIfOdd}>当前求和为奇数再加</button>&nbsp;
                <button onClick={this.incrementAsync}>异步加</button>
            </div>
        )
    }
}

// 使用 connect()() 创建并暴露一个 Count 的容器组件
export default connect(
    state => ({
        count: state.count,
        personList: state.person.length
    }),
    // mapDispatchToProps 一般写法
    // dispatch => ({
    //     jia: (data) => dispatch(createIncrementAction(data)),
    //     jian: (data) => dispatch(createDecrementAction(data)),
    //     async: (data, time) => dispatch(createIncrementAsyncAction(data, time)),
    // })
    // mapDispatchToProps 简写
    {
        increment,
        decrement,
        incrementAsync
    }
)(Count)